#!/bin/sh
# Set new current network manager/exec
# Single argument: new network exec name - sns|net-setup.sh|frisbee
#Exit code: normally 0, but 1 if new exec already running.

NEWEXEC="$1"
if [ -f /root/.connectwizardrc ];then
 . /root/.connectwizardrc #sets CURRENT_EXEC
else
 CURRENT_EXEC='connectwizard' #171126
fi
if [ "$NEWEXEC" != "$CURRENT_EXEC" ];then
 [ "$CURRENT_EXEC" != 'connectwizard' ] \
  && /usr/local/apps/Connect/AppRun --disconnect
 case "$CURRENT_EXEC" in
  net-setup.sh)
   killall dhcpcd 2>/dev/null
   EXECPIDS="$(ps -fC gtkdialog,gtkdialog3 | grep '\WNETWIZ_' | tr -s ' ' | cut -f 2-3 -d ' ' | tr '\n' ' ')"
   ;;
  sns)
   EXECPIDS="$(ps -fC gtkdialog | grep '\WSNS_' | tr -s ' ' | cut -f 2-3 -d ' ' | tr '\n' ' ')"
   ;;
  frisbee)
   [ -x /usr/local/bin/frisbee ] && frisbee --test_active \
    && frisbee --deactivate
   EXECPIDS="$(ps -fC gtkdialog | grep '\WFRISBEE_' | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')$(ps --no-headers -fC frisbee-main,frisbee | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')"
   ;;
  pupdial)
   EXECPIDS="$(ps -fC gtkdialog | grep -E '\WHOTDIALOG|PupDial' | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')$(ps -fC Xdialog | grep 'wmclass pupdial' | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')$(ps --no-headers -fC pupdial_wizard,pupdial | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')"
   ;;
  pgprs)
   EXECPIDS="$(ps -fC gtkdialog | grep '\WPGPRS_' | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')$(ps -fC Xdialog | grep 'wmclass pgprs' | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')$(ps --no-headers -fC pgprs-connect,pgprs-setup,pgprs | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')"
   ;;
  *) EXECPIDS='' ;;
 esac
 [ -n "$EXECPIDS" ] && kill $EXECPIDS
 echo "$CURRENT_EXEC" > /tmp/.connectwizard_previous_exec
 echo "CURRENT_EXEC=$NEWEXEC" > /root/.connectwizardrc #exit code is 0
else
 DUPEXECPIDS="$(ps --no-headers -fC "$NEWEXEC" | grep -wv "$$" | grep -wv "$PPID" | tr -s ' ' | cut -f 2 -d ' ' | tr '\n' ' ')"
 [ -z "$DUPEXECPIDS" ] #set exit code - 1 if duplicate
fi
